import '../../public.dart';
import 'history_list_item.dart';

class HistoryPage extends StatefulWidget {
  const HistoryPage({super.key});

  @override
  State<HistoryPage> createState() => _HistoryPageState();
}

class _HistoryPageState extends State<HistoryPage>
    with TickerProviderStateMixin {
  late TabController _tabController;
  int _selectedStatus = 0; // 0: ALL, 1: Pending, 2: Successful, 3: Rejected

  final GlobalKey<PaginationState<SellRecordPageResponseDto>> _sellRecordKey =
      GlobalKey();
  final GlobalKey<PaginationState<WithdrawRecordPageResponseDto>>
  _withdrawRecordKey = GlobalKey();

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
    _tabController.addListener(() {
      setState(() {
        _selectedStatus = 0;
      });
    });
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  // 卖卡记录请求
  Future<List<SellRecordPageResponseDto>> _getSellRecords(
    int page,
    int pageSize,
  ) async {
    final response = await SellCardApi.getRecordPage(
      SellRecordPageRequestDto(
        pageNum: page,
        pageSize: pageSize,
        sellStatus: _selectedStatus == 0 ? null : _selectedStatus,
      ),
    );
    return response.content?.list ?? [];
  }

  // 提现记录请求
  Future<List<WithdrawRecordPageResponseDto>> _getWithdrawRecords(
    int page,
    int pageSize,
  ) async {
    final response = await ClientWithdrawApi.getRecordPage(
      WithdrawRecordPageRequestDto(
        pageNum: page,
        pageSize: pageSize,
        withdrawStatus: _selectedStatus == 0 ? null : _selectedStatus,
      ),
    );
    return response.content?.list ?? [];
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: SafeArea(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisSize: MainAxisSize.max,
          children: [
            // 页面标题
            Container(
              width: ScreenUtil.width,
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    'Trade History',
                    style: TextStyle(
                      fontSize: 24,
                      fontWeight: FontWeight.w700,
                      color: Colors.grey[800],
                    ),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    'view youer trade history by type',
                    style: TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.w400,
                      color: Colors.grey[600],
                    ),
                  ),
                ],
              ),
            ),
            // TabBar
            Container(
              width: ScreenUtil.width,
              decoration: BoxDecoration(color: Colors.white),
              child: TabBar(
                controller: _tabController,
                indicatorColor: const Color(0xFF3672F4),
                labelColor: const Color(0xFF3672F4),
                unselectedLabelColor: Colors.grey[600],
                dividerColor: Colors.transparent,
                isScrollable: true,
                tabAlignment: TabAlignment.start,
                labelStyle: const TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.w600,
                ),
                unselectedLabelStyle: const TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.w500,
                ),
                tabs: const [
                  Tab(text: 'Gift Cards'),
                  Tab(text: 'Withdrawals'),
                ],
              ),
            ),
            const SizedBox(height: 16),
            // 状态筛选
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16),
              child: Text(
                'Status Filter',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w600,
                  color: Colors.grey[700],
                ),
              ),
            ),
            const SizedBox(height: 8),
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16),
              child: SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                child: Row(
                  children: [
                    _buildStatusButton(0, 'ALL'),
                    const SizedBox(width: 8),
                    _buildStatusButton(1, 'Pending'),
                    const SizedBox(width: 8),
                    _buildStatusButton(2, 'Successful'),
                    const SizedBox(width: 8),
                    _buildStatusButton(3, 'Rejected'),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 16),
            // 内容区域
            Expanded(
              flex: 1,
              child: TabBarView(
                controller: _tabController,
                children: [
                  // Gift cards
                  Pagination<SellRecordPageResponseDto>(
                    key: _sellRecordKey,
                    request: _getSellRecords,
                    itemBuilder: (context, item) =>
                        HistoryListItem.sellRecord(item, context),
                  ),
                  // Withdrawals
                  Pagination<WithdrawRecordPageResponseDto>(
                    key: _withdrawRecordKey,
                    request: _getWithdrawRecords,
                    itemBuilder: (context, item) =>
                        HistoryListItem.withdrawRecord(item, context),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 构建状态按钮
  Widget _buildStatusButton(int value, String label) {
    final isSelected = _selectedStatus == value;
    return GestureDetector(
      onTap: () {
        setState(() {
          _selectedStatus = value;
          if (_tabController.index == 0) {
            _sellRecordKey.currentState?.refresh(true);
          } else {
            _withdrawRecordKey.currentState?.refresh(true);
          }
        });
      },
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        decoration: BoxDecoration(
          color: isSelected ? const Color(0xFF3672F4) : Colors.transparent,
          border: Border.all(color: const Color(0xFF3672F4), width: 1),
          borderRadius: BorderRadius.circular(20),
        ),
        child: Text(
          label,
          style: TextStyle(
            color: isSelected ? Colors.white : const Color(0xFF3672F4),
            fontSize: 14,
            fontWeight: isSelected ? FontWeight.w600 : FontWeight.w500,
          ),
        ),
      ),
    );
  }
}
